package cn.wolfcode.luowowo.website.controller;

import cn.wolfcode.luowowo.cache.service.IUesrInfoCacheService;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.common.util.Consts;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.member.service.IUserInfoService;
import cn.wolfcode.luowowo.website.annotation.UserParam;
import com.alibaba.dubbo.config.annotation.Reference;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
public class LoginController {
    //@Autowired : 如果模块 间的引入
    @Reference  //不同服务间引入
    private IUserInfoService userInfoService;
    @Reference
    private IUesrInfoCacheService redisCacheService;


    @RequestMapping("/index")
    public String index(HttpServletRequest request, @UserParam UserInfo userInfo) {
        //因为这个时候我们需要共享数据数据,所以我们要把用户对象存储到会话中
        request.getSession().setAttribute("userInfo", userInfo);




















        return "index/index";
    }


    @ResponseBody
    @RequestMapping("/checkPhone")
    public boolean checkPhone(String phone) {
        return !userInfoService.checkPhoneByphone(phone);
    }

    /**
     * 首先登陆的时候拿到账号和密码去到后台需要校验账号和密码不为空
     * 通过后,校验是不是成功登陆
     * 成功登陆后要把数据在所有服务器中共享,所以要把数据存入到redis
     * 这里redis的key需要设计枚举
     * 前缀以及唯一性,以及时效性
     * 存入redis后把token传回给前台,并且告诉前台登陆成功
     * 并且在前台把cookie存入token的值传送给浏览器
     *
     * @param username
     * @param password
     */
    @ResponseBody
    @RequestMapping("/userLogin")
    public AjaxResult userLogin(String username, String password, HttpServletResponse response,HttpServletRequest request) {
        String token = userInfoService.userLogin(username, password);
        //设计cookie
        //这里为安全起见,名字不起token
        Cookie cookie = new Cookie("faceTime", token);
        //设置有效范围
        cookie.setPath("/");
        //设置有效时间
        cookie.setMaxAge(Consts.USER_INFO_TOKEN_VAI_TIME * 60);
        response.addCookie(cookie);
        UserInfo userInfo = redisCacheService.getUserInfo(token);
        request.getSession().setAttribute("userInfo", userInfo);
        return new AjaxResult(true, "登陆成功");
    }

    @ResponseBody
    @RequestMapping("/userRegist")
    public AjaxResult userRegist(String phone, String nickname, String password, String rpassword, String verifyCode) {
        userInfoService.userRegist(phone, nickname, password, rpassword, verifyCode);
        return new AjaxResult(true, "注册成功");
    }


    @ResponseBody
    @RequestMapping("/userinfo")
    public UserInfo userRegist(@UserParam UserInfo userInfo) {
        return userInfo;
    }


}
